import React, { createRef, PureComponent } from "react";
import { FormContext } from "./FormContext";
export default class MyFormItem extends PureComponent {
      constructor(props) {
            super(props);
            this.state = {
                  errorMsg: "",
            };
            this.unmountWatcher = createRef(null);
      }
      static contextType = FormContext;

      componentDidMount() { 
            const formData = this.context;
            this.unmountWatcher = formData.setWatcherUpdate(this);
            // 注册校验规则

      }

      componentWillUnmount() {
            this.unmountWatcher();
            // 取消校验规则

      }

      // 校验规则
      validateValue = () => {
            
      }

      renderInfo = () => {
            this.forceUpdate();
      };

      inputChangeData = (e) => {
            const { name } = this.props;
            const formData = this.context;
            let value = e.target.value;
            formData.setStore(name, value);
      };

      render() {
            const { children, label, rules, name } = this.props;
            console.log(rules, name);
            const { errorMsg } = this.state;
            const formData = this.context;
            let cloneChilren = React.cloneElement(children, {
                  value: formData.getStoreByKey(name),
                  onChange: this.inputChangeData,
            });
            return (
                  <div className="my-form-item">
                        <span>{label ? label + ":" : null}</span>
                        {cloneChilren} 
                        {name && errorMsg ? (
                              <div className="red">{errorMsg}</div>
                        ) : null}
                  </div>
            );
      }
}
